package com.xian.array;
/**
 * 定义一个自己的数组集合类
 * @author jiao
 *
 */
public class MyArrayList {
	
	
	private int[] arr;
	private int size; //数组大小
	private int cursor; //最后插入数据游标
	
	private static final int DEFAULT_SIZE = 10;
	
	public MyArrayList() {
		this(DEFAULT_SIZE);
		
	}
	
	public MyArrayList(int size) {
		if(size > DEFAULT_SIZE) {
			arr = new int [size];
			this.size = size;
		} else {
			arr = new int [DEFAULT_SIZE];
			this.size = DEFAULT_SIZE;
		}
			
		
	}
	
		
	/**
	 * 数组大小
	 * @return
	 */
	public int size() {
		return size;
	}
	
	// 添加元素
	public void add(int element) {
		checkCapacity();
		checkIndex(cursor);
		arr[cursor] = element;
		cursor++; //游标+1
	}
	
	//在某个位置插入数字(覆盖)
	public void add(int index, int element) {
		checkCapacity();
		checkIndex(index);
		arr[index] = element;
	}
	
	
	// 查找元素
	public int find(int index) {
		checkIndex(index);
		return arr[index];
	}
	
	// 删除元素
	public void remove(int index) {
		checkIndex(index);
		arr[index] = 0; //删除可以直接置空或置0
	}
	
	//清空数组
	public void clear() {
		for(int i = 0; i<size; i++) {
			arr[i] = 0;
		}
	}
	
	// 遍历元素
	public void showArr() {
		for(int i = 0; i<size; i++) {
			System.out.print(i+"=>"+arr[i]+", ");
		}
		System.out.println();
	}
	
	
	//检查传入脚表
	private void checkIndex(int index) {
		if(index < 0 || index >= size) {
			throw new ArrayIndexOutOfBoundsException("传入数组脚本越界:index="+index+",size="+size);
		}
	}
	

	//检查容量
	private void checkCapacity(){
		if(cursor >= size) {
			size = size + size/2;
			int [] newArr = new int [size];
			for (int i=0; i<cursor; i++) {
				newArr[i] = arr[i];
			}
			arr = newArr;
		}
	}
	
	
	
	

}
